/*
 * @Author: DUST
 * @Date: 2023-05-26 11:34:56
 * @LastEditors: DUST
 * @LastEditTime: 2023-11-27 11:24:08
 * @FilePath: \business-card-system\server\app\index.ts
 * @Description:
 * undefined
 */
import path from "path";
import dotenv from "dotenv";
const env = dotenv.config({ path: path.resolve(process.cwd(), `.env.${process.env.NODE_ENV}`) }); //config()中是配置.env文件的位置，如果在根目录，此处括号中可以留空

console.log("服务启动目录：", process.cwd())
console.log("配置文件完整目录：", path.resolve(process.cwd(), `.env.${process.env.NODE_ENV}`));
console.log("当前配置：", env.parsed)

import Koa, { Context } from "koa";
import koaBody from "koa-body";
import { Server } from "http";
import router from "./router";
import foreEndRouter from "./router/foreEnd";
import accessLogMIddleware from "./middleware/accessLogMIddleware";
// 引入数据库使用
import db from "./db";
import KoaStatic from "koa-static";
import cors from "koa2-cors";

db();

const app = new Koa();
app.proxy = true;
app
  .use(
    koaBody({
      multipart: true,
      formidable: {
        maxFieldsSize: 200 * 1024 * 1024,
        // 上传目录，意思是说上传到当前项目的/public/upload目录下
        // uploadDir: path.join(__dirname, "/public/upload"),
        // 是否保留拓展名
        keepExtensions: true,
      }, // 文件上传大小限制
    })
  )
  .use(KoaStatic(path.join(__dirname, "..", "public")))
  .use(accessLogMIddleware)
  .use(router.routes())
  // .use(async (ctx, next) => {
  //   ctx.set('Access-Control-Allow-Origin', '*');
  //   ctx.set('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');
  //   ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  //   await next();
  // })
  .use(cors(
    //   {
    //   origin: (ctx: Context): boolean | string => { //设置允许来自指定域名请求
    //     const whiteList: Array<string> = []; //可跨域白名单，这里设置前端的
    //     let url: string | undefined = ctx.header.origin;
    //     console.log("url", ctx.header);
    //     if(url && whiteList.includes(url)){
    //       return url
    //     }
    //     return true //默认允许本地请求3000端口可跨域
    //   },
    //   exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    //   maxAge: 50000,
    //   credentials: true,
    //   // allowMethods: ['GET', 'POST', 'DELETE'],
    //   allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    // }
  ))
  .use(foreEndRouter.routes());

const run = (port: any): Server => {
  console.log(`服务启动本地地址：http://localhost:${port}/`);
  return app.listen(port);
};

export default run;
